const Joi = require('joi');
const Device = require('../models/device.model');

const deviceSchema = Joi.object({
  name: Joi.string().default(''),
  sn: Joi.string().default(''),
  pub: Joi.string().default(''),
  sub: Joi.string().default(''),
  model: Joi.string().default(''),
  position: Joi.string().default(''),
  online: Joi.number().default(0),
  value: Joi.string().default(''),
})


module.exports = {
  insert,
  findOne, 
  findAll, 
  remove,
  edit,
}

async function insert(device) {
  console.log(device)
  device = await Joi.validate(device, deviceSchema, { abortEarly: false });
  const res = Device.create(device);
  return res;
}

async function findAll(user) {
  const device = await Device.findAll();
  console.log(device)
  if (device === null) {
    return false;
  } else {
    return device;
  }
}

async function findOne(id) {
  return Device.findOne({"_id": id}, function(err, doc){
    if(err) {
      return err 
    }
    return doc
  }) 
}

async function edit(device) {
  const res = await Device.update(device, { where: { id: device.id } });
  return res
}

async function remove(id) {
  return Device.deleteOne({"_id": id}, function(err, doc){
    if(err) {
      return false
    }
    return true
  }) 
}
